package com.dailyblue.project.smbms.alibaba.gateway.filter;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.project.smbms.alibaba.commons.util.JsonResult;
import com.dailyblue.project.smbms.alibaba.commons.util.JwtConfig;
import com.dailyblue.project.smbms.alibaba.commons.util.ResultCode;
import com.dailyblue.project.smbms.alibaba.commons.util.ResultTool;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

// 判断用户是否登陆
@Component
@Slf4j
public class CheckLoginGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("开始校验用户是否登陆");
        URI uri = exchange.getRequest().getURI();
        log.info("是否是登陆操作?{}",uri.toString().contains("smbms-login/login"));
        if(uri.toString().contains("smbms-login/login")){
            return chain.filter(exchange);
        }
        log.info("uri:{}", uri);
        // 首先获取到header中的token
        List<String> tokens = exchange.getRequest().getHeaders().get("token");
        if (tokens == null || tokens.size() == 0) {
            log.info("未携带token，用户未登录！");
            // 输出错误
            return error(exchange);
        }
        String headerToken = tokens.get(0);
        log.info("携带的token:{}",headerToken);
        if (!JwtConfig.checkToken(headerToken)) {
            log.info("token不合法，用户未登录！");
            return error(exchange);
        }
        Claims claims = JwtConfig.parseJWT(headerToken);

        String id = claims.get("id").toString();
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        String redisToken = valueOperations.get("TOKEN:" + id);
        if (!redisToken.equals(headerToken)) {
            log.info("token未匹配，用户未登录！");
            return error(exchange);
        }
        log.info("登陆成功，header:{},redis:{}", headerToken, redisToken);
        return chain.filter(exchange);
    }

    private Mono<Void> error(ServerWebExchange exchange) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(403));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        JsonResult result = ResultTool.fail(ResultCode.USER_NOT_LOGIN);
        String str = JSONArray.toJSONString(result);
        DataBuffer data = response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(data));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
